<template>
  <el-container>
    <!-- 左侧院系树 -->
    <el-scrollbar style="height: 100vh; width: 20%">
      <el-aside style="width: 100%">
        <el-table
          :data="departments"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          max-height="800px"
          border
          default-expand-all
          highlight-current-row
          @row-click="departmentTreeRowClick"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="name" label="院系名称">
            <template slot="header" slot-scope="scope">
              <span>院系名称</span>
              <el-input
                v-model="search"
                @input="changeValue"
                @keyup.enter.native="handleSearch"
                style="width: 60%; margin-left: 20px"
                size="mini"
                placeholder="输入关键字搜索"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-aside>
    </el-scrollbar>
    <el-dialog
      :title="isAdd ? '专业添加' : '专业编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="30%"
      center
    >
      <el-form
        ref="majorForm"
        :model="majorForm"
        label-width="100px"
        fullscreenLoading
        :rules="majorFormRules"
        class="formStyle"
      >
        <el-form-item label="专业名称" prop="name">
          <el-input
            v-model="majorForm.name"
            placeholder="请输入专业名称"
            class="inputWdith"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属院系">
          <el-select
            v-model="majorForm.departmentId"
            placeholder="请选择院系"
            disabled
          >
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('majorForm')"
            @keydown.enter="submitForm('majorForm')"
            v-loading.fullscreen.lock="fullscreenLoading"
            >确认</el-button
          >
          <el-button @click="resetForm('departmentForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button" v-show="depRowId">
          <el-button type="primary" size="small" round @click="handleAdd()"
            >新增按钮</el-button
          >
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入专业名"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="majorName"
          >
          </el-input>
          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="majorTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="majors"
            fit
            max-height="700"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
            @row-click="rowClick"
          >
            <el-table-column prop="id" label="专业编号"> </el-table-column>
            <el-table-column prop="name" label="专业名称"> </el-table-column>
            <el-table-column prop="department" label="所属院系">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            hide-on-single-page
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { Message } from 'element-ui';
import throttle from 'lodash/throttle'; //  节流
import { mapGetters } from 'vuex';
export default {
  name: 'MajorMng',
  props: ['departmentId'],
  data() {
    let validateNameIsRepeat = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('请输入专业名称')]);
      }
      if (this.isAdd) {
        // 检查是否重名
        let result = await this.$store.dispatch(
          'AcademyMng/checkIsRepeatForMajorName',
          value
        );
        return result.data.flag
          ? callback()
          : callback([new Error(result.message)]);
      }
    };
    return {
      isAdd: false, // 是否为点击新增按钮打开的模态窗口
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总数
      condition: {},
      majorName: '',
      majors: [],
      loading: false, // 遮罩层
      majorForm: {}, // 院系表单对象
      fullscreenLoading: false, // 遮罩层
      departments: [], // 院系列表
      // 映射关系
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      centerDialogVisible: false, // 弹出框
      search: '', // 表头搜索
      depRowId: '', // 院系编号
      majorFormRules: {
        name: [
          {
            required: true,
            validator: validateNameIsRepeat,
            trigger: 'blur',
          },
        ],
      },
    };
  },
  watch: {
    majorList() {
      this.$set(this, 'majors', this.majorList);
      this.loading = false;
    },
    majorIPage() {
      this.currentPage = this.majorIPage.currentPage;
      this.pageSize = this.majorIPage.pageSize;
      this.total = this.majorIPage.total;
    },
    departmentListForIdAndName() {
      this.$set(this, 'departments', this.departmentListForIdAndName);
      this.loading = false;
    },
    // 根据院系编号查询出来的专业集合
    majorsByDepId() {
      this.$set(this, 'majors', this.majorsByDepId);
      this.loading = false;
    },
    search() {
      this.departments = this.departmentListForIdAndName.filter((item) => {
        if (item.name.indexOf(this.search) != -1) {
          return true;
        }
      });
    },
  },
  computed: {
    ...mapGetters('AcademyMng', ['majorList', 'majorIPage', 'majorsByDepId']),
    ...mapGetters('AcademyMng', ['departmentListForIdAndName']),
  },
  mounted() {
    // 由院系组件路由至专业组件时，执行。
    if (this.departmentId) {
      this.getMajorListByDepartmentId(this.departmentId);
    }
    this.getDepartmentList();
  },
  methods: {
    // // 左侧院系搜索
    // handleSearch() {
    //   if (this.search) {
    //     this.departments = this.departmentListForIdAndName.filter((item) => {
    //       if (item.name.indexOf(this.search) != -1) {
    //         return true;
    //       }
    //     });
    //   } else {
    //     this.departments = this.departmentListForIdAndName;
    //   }
    // },
    changeValue(e) {
      this.$forceUpdate();
    },

    // 根据院系编号查询专业信息列表
    getMajorListByDepartmentId(departmentId) {
      this.$store.dispatch(
        'AcademyMng/getMajorListByDepartmentId',
        departmentId
      );
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            // 接收返回的结果
            let result = {};
            if (this.isAdd) {
              let paramsArray = [];
              // 发送请求
              let params = {
                ...this.majorForm,
              };
              paramsArray.push(params);

              result = await this.$store.dispatch(
                'AcademyMng/batchAddMajorList',
                paramsArray
              );
            } else {
              result = await this.$store.dispatch(
                'AcademyMng/editMajor',
                this.majorForm
              );
            }
            // 执行成功返回结果，
            // 更新专业列表
            if (this.majorForm.departmentId) {
              this.getMajorListByDepartmentId(this.majorForm.departmentId);
            }
            // if (this.depRowId) {
            //   this.getMajorListByDepartmentId(this.depRowId);
            // } else {
            //   this.getMajorList();
            // }
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            this.fullscreenLoading = false; // 关闭遮罩层
            this.isAdd = false; // 重置表单状态
            this.centerDialogVisible = false; // 关闭模态窗口
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 点击左侧院系树行
    async departmentTreeRowClick(row) {
      this.loading = true;
      // 根据院系编号查询专业集合
      this.depRowId = row.id;

      this.getMajorListByDepartmentId(row.id);
    },
    // 获取院系列表
    getDepartmentList() {
      this.loading = true;
      this.$store.dispatch('AcademyMng/getDepartmentListForIdAndName');
    },
    // 刷新专业列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getMajorListByDepartmentId(this.depRowId);
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 删除专业
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('AcademyMng/batchDelMajor', [
            row.id,
          ]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getMajorListByDepartmentId(this.depRowId);
        })
        .catch(() => {
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
        });
    },

    // 编辑专业
    handEdit(row) {
      this.majorForm = row;
      this.centerDialogVisible = true;
    },

    // 新增专业
    handleAdd() {
      this.centerDialogVisible = true;
      this.majorForm = {};
      this.majorForm.departmentId = this.depRowId;
      this.isAdd = true;
    },

    // 条件查询
    async queryByCondition() {
      // 初始化条件查询参数
      this.condition = {};
      if (this.majorName) {
        this.condition.name = this.majorName;
      }
      this.condition.departmentId = this.depRowId;
      await this.getMajorList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getMajorList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getMajorList();
    },

    // 点击行,跳转至专业页面,显示对应的专业
    rowClick(row) {},

    // 查询院系列表
    getMajorList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      this.$store.dispatch('AcademyMng/getMajorList', params);
    },

    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },
  },
};
</script>

<style lang="scss" scoped>
/* 分页居中 */
.block {
  text-align: center;
}
</style>
